package vip.xiaonuo.common.util;

import lombok.extern.slf4j.Slf4j;

import javax.crypto.Cipher;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;

/**
 * rsa加密
 */
@Slf4j
public class CommonRSAUtil {

    public static String publicKey = "MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBALM3ZtdHNjm3Iu+zrrERMrvBv8vBAjIr+MBp8xvyLwT+3nOrbuGjuYLa2+ADv+avfUIDQm9txmKyLzyo7hS281UCAwEAAQ==";

    public static String privateKey = "MIIBVQIBADANBgkqhkiG9w0BAQEFAASCAT8wggE7AgEAAkEAszdm10c2Obci77OusREyu8G/y8ECMiv4wGnzG/IvBP7ec6tu4aO5gtrb4AO/5q99QgNCb23GYrIvPKjuFLbzVQIDAQABAkBCj0zun1AQV2fuRnmW4aBKA0dMUT6Ti6kzLSZRNr0nyTFTgNUNt2rdZT1Xe8Ia0be1M6YNj1HaoTlbjOiFmaKBAiEA4nUOgxoB3ItiP+tZKdxime45L//1cwjSbtBgld5F+L0CIQDKmKcuLr4WIdXPGyZB1GjhZ0ZbSgM/xIhpv8+koPEKeQIgXyGDfimPvKFFHcr1QvOU7Es59OMWrkN3exvIZ0zfohUCIQC7VNHpQzFjF6AzI+CJKFZebfdBfDtq4FheqAzhJiwbyQIhAKVLAk81x1Hjb8VemHos0mB2uAAlXE5E9BQGPcuAmZIv";

    //加密 每次加密的值都不一样，加密时会随机生成 填充字节 , 这是 主动安全防护，防止重复密文被暴力破解
    public static String encrypt(String plainText,String pubKey) {
        // 1. 解码Base64格式的公钥
        byte[] publicBytes = Base64.getDecoder().decode(pubKey);
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publicBytes);
        Cipher cipher = null;
        String rsp = null;

        try {
            // 2. 生成公钥对象
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            PublicKey pk = keyFactory.generatePublic(keySpec);

            // 3. 初始化加密器
            cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
            cipher.init(Cipher.ENCRYPT_MODE, pk);


            // 4. 执行加密
            byte[] encryptedBytes = cipher.doFinal(plainText.getBytes("UTF-8"));

            // 5. 返回Base64编码的加密结果
            rsp = Base64.getEncoder().encodeToString(encryptedBytes);
        } catch (Exception e) {
            log.error("RSA加密失败", e);
        }
        return rsp;
    }

    //解密
    public static String decrypt(String encryptedText) {
        // 1. 解码Base64私钥
        byte[] privateBytes = Base64.getDecoder().decode(privateKey);
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(privateBytes);
        Cipher cipher = null;
        String rsp = null;

        try {
            // 2. 生成私钥对象
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            PrivateKey privKey = keyFactory.generatePrivate(keySpec);

            // 3. 初始化解密器
            cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
            cipher.init(Cipher.DECRYPT_MODE, privKey);

            // 4. 执行解密
            byte[] decryptedBytes = cipher.doFinal(Base64.getDecoder().decode(encryptedText));

            // 5. 返回原始文本
            rsp = new String(decryptedBytes, "UTF-8");
        } catch (Exception e) {
            log.error("RSA解密失败", e);
        }
        return rsp;
    }

    public static void main(String[] args) throws Exception {
        String plainText = "白双燕";

        String encryptedText = encrypt(plainText,publicKey);
        log.info("加密结果: {}", encryptedText);

        String decryptedText = decrypt(encryptedText);
        log.info("解密结果: {} ", decryptedText);
    }
}
